package evs.security;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;

import evs.gateway.HttpHelper;
import evs.location.EvsException;

public abstract class SecureServlet extends HttpServlet
{
    private static final long serialVersionUID = -9187719256306612745L;
    
    protected ISecurityManager _securityManager;
    protected final HttpHelper _http = new HttpHelper();
    
    @Override
    public void init() throws ServletException
    {
        try
        {
            _securityManager = new SecurityManager( this.getServletName(), "123456" );
            
            String configFileName = this.getInitParameter( "security-config-file" );
            _securityManager.initialize( configFileName );
                        
            String virtualIp = this.getInitParameter( "virtual-ip" );
            
            if ( virtualIp != null )
            {
                _http.addCustomHeaderField( "x-virtual-ip", virtualIp );                
            }
            
        }
        catch ( Exception e )
        {
            throw new ServletException( e );
        }
    }
    
    protected void _checkAllowRequest( ServletRequest request ) throws EvsException
    {
        if ( _allowOnlyLocalAccess() && !_securityManager.isLocalRequest( request ) )
            throw new EvsException( HttpServletResponse.SC_FORBIDDEN, 
                            "Cannot allow request from " + request.getRemoteAddr() );
    }
    
    protected abstract boolean _allowOnlyLocalAccess();
}
